<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;


/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class UserController extends HomeController
{

    /* 用户中心首页 */
    public function index()
    {
        $uid = $this->uid;

        $ptyh = M('ptyh')->find($uid);
        $kbxx = D('Kbxx')->where('uid=' . $this->uid)->find();
        $isMashang = empty($kbxx) ? $isMashang = 0 : $isMashang = 1;
//        $total1 = D('Dingdan')->where(['uid' => $uid, 'status' => 1])->sum('yh_money');     //订单获得
        $total2 = D('Dividend')->where(['uid' => $uid, 'status' => 1])->sum('divide'); //推广获得
        $total3 = D('Split')->where(['uid' => $uid, 'status' => 1])->sum('sh_money'); //口碑收益获得
        is_null($total3) ? $yongjin = 0.00 : $yongjin = $total3; //口碑收益是佣金
//        $fenrun = ($total1 * 100 + $total2 * 100) / 100; //分润 = 订单 + 推广
        is_null($total2) ? $fenrun = 0.00 : $fenrun = $total2;

//        M('gather')->where(['uid' => $this->uid])->save(['yongjin' => $yongjin,'fenrun' =>$fenrun ]);

        $gather = M('gather')->where(['uid' => $this->uid])->find();
        $this->showSuccess('', ['is_mashang' => $isMashang,'yongjin' => $gather['yongjin'], 'fenrun' => $gather['fenrun'], 'info' => $ptyh, 'userInfo' => $this->userInfo]);
    }


    /**
     * 登录
     *
     */
    public function login()
    {

        if (IS_POST) {
            $account = I('post.account');
            $password = I('post.password');
            $one = M('Ptyh')->where("account=$account")->find();//同一个账号只存在一个，否则无法区分使用哪个账号登录
            if (empty($one)) {
                $this->showError('用户不存在');

            } else {
                $p = md5($password);
                if ($p != $one['password']) {

                    $this->showError('密码错误');
                } else {

                    $avatar = M('member')->where(array('uid' => $one['wx_uid']))->getField('headimgurl');
                    $data = array(
                        'account' => md5($account),
                        'login' => 1,
                        'uid' => $one['uid'],
                        'name' => $one['name'],
                        'avatar' => $avatar
                    );

//                    $this->cookie('user', $data, time() + 3600 * 24);
                    //redis 存储
                    $client = new \Predis\Client(C('REDIS'));
//                    $client->set('shouyin-uid'.$one['openid'],$one['uid']);
                    $client->hmset('shouyin-user-' . $one['uid'], ['account' => $account, 'login' => 1, 'uid' => $one['uid'], 'name' => $one['name'], 'avatar' => $avatar]);
                    $this->uid = $one['uid'];
                    $this->showSuccess('登录成功', $client->hgetall('shouyin-user-' . $one['uid']));

                }
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {

        $uid = I('uid');
        $client = new \Predis\Client(C('REDIS'));
//        $client->del('shouyin-uid');
        $client->del('shouyin-user-' . $uid);
        $this->showSuccess('退出登录');
    }

    /**
     * 忘记密码
     */
    public function forget()
    {
        if (IS_POST) {
            $account = I('post.account');
            $np = I('post.npassword');
            $code = I('post.code');

            $yh = D('Ptyh')->where(['account' => $account])->find();
            if (empty($yh)) {

                $this->showError('该账号不存在');
            }
            if (empty($np)) {

                $this->showError('请输入密码');
            }


            if (empty($code)) {

                $this->showError('请输入手机验证码');
            } else {
                $smsLogic = new \Common\Model\SmsLogic();
                $smsResult = $smsLogic->checkCode($account,$code,'forget');

//                $smsResult['code'] = 1;
                if($smsResult['code'] != 1)  $this->showError($smsResult['msg']);

            }

            $res  = M('Ptyh')->where(['account' => $account])->save(['password' => md5($np)]);
            if($res !== false){
                $this->showSuccess('修改成功');
            }else{
                $this->showError('修改失败');
            }
        }
    }


    /**
     * 修改密码
     */
    public function change()
    {
        $p = I('post.password');
        $np = I('post.npassword');
        $code = I('post.code');
        $uid = $this->uid;
        $one = D('Ptyh')->where(['uid' => $uid])->find();
        // print_r($one);
        // echo $this->uid;die;
        if (empty($p) || empty($np)) {

            $this->showError('请填写密码');
        }
        if ($p == $np) {

            $this->showError('输入的新旧密码不可相同');
        }
        if (md5($p) != $one['password']) {

            $this->showError('旧密码输入错误');
        }
        if (md5($np) == $one['password']) {

            $this->showError('新旧密码不可相同');
        }

        if (empty($code)) {
            $this->showError('请输入手机验证码');
        } else {
            $smsLogic = new \Common\Model\SmsLogic();
            $smsResult = $smsLogic->checkCode($one['account'],$code,'changepwd');
            if($smsResult['code'] != 1)  $this->showError($smsResult['msg']);
        }

        $id = D('Ptyh')->where(['uid' => $uid])->save(['password' => md5($np)]);
        if ($id > 0) {
            $this->showSuccess('密码修改成功');
        } else {
            $this->showError('密码修改失败');
        }



    }


    /**
     * 修改密码/重置密码 发送短信验证码
     */

    public function get_code()
    {
        // print_r('验证码暂不使用，请晚点重试');die;
        $mobile = I('post.mobile');
        $type = I('post.type', 2);
        if (empty($mobile)) {

            $this->showError('手机号码不可为空');
        }
        // type=1 资料认证  2 修改密码/重置密码  3 后台登录

        $yh = D('Ptyh')->where(['phone' => $mobile])->find();

        if (empty($yh)) {

            $this->showError('该用户不存在');
        }


        $one = D('Active')->where(['phone' => $mobile, 'type' => 2])->find();


        $code = '';


        if (!empty($one)) {
//            if (($one['time'] + 180) > time()) {
            if (false) {
                // 验证码仍有效
                $this->showError('验证码3分钟有效, 请查看手机短信');
            } else {
                // 验证码失效
                $id = D('Active')->where(['phone' => $mobile, 'type' => 2])->delete();


                for ($i = 0; $i < 6; $i++) {
                    $code .= rand(1, 9);
                }
                $data = array(
                    'phone' => $mobile,
                    'code' => $code,
                    'time' => time(),
                    'type' => $type,
                );


                $id = D('Active')->add($data);
                if ($id > 0) {
                    $re = $this->send_post($code, $mobile, $type);
                    $re = json_decode($re, true);
                    if ($re['code'] == '000000') {

                        $this->showSuccess('发送成功');
                    } else {

                        $this->showError($re['msg']);
                    }
                }
            }

        } else {

            for ($i = 0; $i < 6; $i++) {
                $code .= rand(1, 9);
            }
            $data = array(
                'phone' => $mobile,
                'code' => $code,
                'time' => time(),
                'type' => $type,
            );


            $id = D('Active')->add($data);
            if ($id > 0) {
                $re = $this->send_post($code, $mobile, $type);
                $re = json_decode($re, true);
                if ($re['code'] == '000000') {

                    $this->showSuccess('发送成功');
                } else {
                    $this->showError($re['msg']);
                }
            }

        }
    }


    /**
     * 发送短信--post请求
     * @param $code
     * @param $mobile
     * @param $type
     * @return mixed
     */
    public function send_post($code, $mobile, $type)
    {

        require_once('ThinkPHP/Library/Vendor/sms/lib/Ucpaas.class.php');
        require_once('ThinkPHP/Library/Vendor/sms/serverSid.php');


        $appid = "0dce834d518d4c24b1a73e02453aee0c"; //应用的ID，可在开发者控制台内的短信产品下查看
        if ($type == 3) { // 1 认证资料  2 修改、重置 3 后台登录
            $templateid = "314554";    //可在后台短信产品→选择接入的应用→短信模板-模板ID，查看该模板ID
        } else if ($type == 2) {
            $templateid = "314525";
        } else if ($type == 1) {
            $templateid = "314526";
        }

        $param = $code; //多个参数使用英文逗号隔开（如：param=“a,b,c”），如为参数则留空
        $mobile = $mobile;
        $uid = "";

        //70字内（含70字）计一条，超过70字，按67字/条计费，超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。

        return $ucpass->SendSms($appid, $templateid, $param, $mobile, $uid);
    }


    /**
     * 列表
     */
    public function question_index()
    {
        $data = M('question')->select();
        $this->showSuccess('', $data);
    }

    /**
     * 详情
     */
    public function question_detail()
    {
        $id = I('id');
        $data = M('question')->find($id);
        $this->showSuccess('', $data);

    }

    /**
     * 公告弹窗
     */
    public function gonggao()
    {
        $uid = $this->uid;
        $gonggao = M('gg')->order('id desc')->find();
        $client = new \Predis\Client(C('REDIS'));
        $key = 'gonggaoYueDu-' . $uid . '-' . $gonggao['id'];
        if (!$client->exists($key)) {
            $client->set($key, 1);
            $this->showSuccess('公告阅读', $gonggao);
        } else {
            //存在
            if ($client->get($key) < 3) {
                $client->incr($key);
                $this->showSuccess('公告阅读', $gonggao);
            } else {
                $this->showError('此公告已阅读3次');
            }
        }

    }

    /**
     * 公告列表
     */
    public function gonggao_index()
    {
        $gonggao = M('gg')->order('id desc')->select();
        $this->showSuccess('', $gonggao);
    }

    /**
     * 公告详情
     */
    public function gonggao_detail()
    {
        $id = I('id');
        $detail = M('gg')->find($id);
        $this->showSuccess('', $detail);
    }

    /**
     * 用户提现
     * $
     */

    public function tixian()
    {

        if (IS_POST) {

// print_r($_POST);die;
            $info = D('Tongdao')->find();
            if ($info['tixian'] == 0) {

                $this->showError('平台暂无法手动提现，每天自动打款时间为23:59！敬请谅解。');
            }

            $uid = I('post.uid');
            $ga = D('Gather')->where("uid=$uid")->find();
            if ($ga['frozen'] == 0) {

                $this->showError('该账号已被冻结，暂时无法提现。。');
            }

//            $alipay = I('post.alipay');
            $amount = I('post.money');
            $type = I('post.type');
            $out_biz_no = date("YmdHis") . rand(100000, 999999);
            $one = D('Ptyh')->where('uid=' . $uid)->find();
            $alipay = $one['alipay'];
            $payee_real_name = $one['name'];
            $payer_show_name = '绿叶收银台';
            $time = time();

            // 判断单笔累计、用户余额是否超出、支付宝当日累计支付
            if (10 > $amount) {

                $this->showError('提现金额不可低于10元。');
            }
            if ($amount > 5000) {

                $this->showError('单笔提现不可超过5千。');
            }
            $gather = D('Gather')->where("uid=" . $uid)->find();




            if ($type == 1) {
                //分润

                if ($gather['fenrun'] < ($amount)) {

                    $this->showError('提现金额不可超过用户分润余额。');

                }

            } else {
                if ($gather['yongjin'] < ($amount)) {

                    $this->showError('提现金额不可超过用户佣金余额。');

                }

            }


            // 判断结束
            $time = time();
            $extract = array(
                'uid' => $uid,
                'money' => ($amount*100-100)/100,//存入的是扣除手续费的金额
                'time' => $time,
                'status' => 0,
                'out_biz_no' => $out_biz_no,
                'type' => $type
            );
            $id = D('Extract')->add($extract);
            Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
            $transfer = new \Alipay;
            $remark = '商户提现';
            $_amount = ($amount*100-100)/100;//实际到款

            $adata = D('Adata')->where(['id' => 1])->find();

            // 查看当日提现总金额  超过95万则使用另一个支付宝
            $time1 = strtotime(date("Ymd", strtotime("+1 day")));
            $time2 = strtotime(date("Ymd"));
            $money = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

            $result = $transfer->transfer8($out_biz_no, $alipay, $_amount, $remark, $payee_real_name, $payer_show_name, $adata);

            if (empty($result->sub_msg) && $result->out_biz_no == $out_biz_no) {
                // 说明是成功的   1、提现状态修改 2、提现次数、用户余额修改
                $out_no = $result->out_biz_no;
                $order_id = $result->order_id;
                $extract = D('Extract')->where('out_biz_no=' . $out_no)->find();

                D('Extract')->where('out_biz_no=' . $out_no)->save(['status' => 1, 'order_id' => $order_id]);

                $one = D('Gather')->where('uid=' . $extract['uid'])->find();

                $count = $one['count'] + 1;

                if ($type == 1) {
                    //分润
                    $money = $one['fenrun'] - $amount;

                    D('Gather')->where('uid=' . $extract['uid'])->save(['fenrun' => $money, 'count' => $count]);

                    D('Extract')->where('id=' . $extract['id'])->save(['t_fenrun' => $money]);
                } else {
                    $money = $one['yongjin'] - $amount;

                    D('Gather')->where('uid=' . $extract['uid'])->save(['yongjin' => $money, 'count' => $count]);

                    D('Extract')->where('id=' . $extract['id'])->save(['t_yongjin' => $money]);
                }


                $data = [
                    'name' => $payee_real_name,
                    'time' => date("Y-m-d H:i:s", $time),
                    'money' => $amount,
                    'remark' => '提现单号：' . $out_biz_no . '，如有疑问请联系客服',
                ];
                $member = D('Ptyh')->where(['uid' => $uid])->find();
                if (!empty($member)) {
                    D('Notice')->weixin(11, $member['wx_uid'], $data);
                } else {
                    // echo '未绑定微信';die;
                }


                $this->showSuccess('提现成功。');

            } else {
                D('Extract')->where('out_biz_no=' . $out_biz_no)->save(['cause' => $result->sub_msg]);

                $this->showError('提现失败。');

            }


        }
    }

    /**
     * 提现页面
     */
    public function tixian_page()
    {
        $time = intval(date('G'));
        $list = D('Ptyh')->where("uid=" . $this->uid)->find();
        $gather = D('Gather')->where("uid=" . $this->uid)->find();
        $type = array('0' => '佣金', '1' => '分润');



    }


    // 提现记录列表
    public function tixianLog()
    {
        $map['uid'] = array('eq', $this->uid);
        $startTime = I('get.start_time');
        $endTime = I('get.end_time');
        $startTime ? $map['time'] = array('gt', strtotime($startTime)) : '';
        $endTime ? $map['time'] = array('lt', strtotime($endTime)) : '';

        ($startTime && $endTime) ? array(array('gt', strtotime($startTime)), array('lt', strtotime($endTime)), 'and') : '';

        $map['uid'] = array('eq', $this->uid);
        $order = 'time desc';
        $list = $this->lists('Extract', $map, $order);

        foreach ($list as $k => $v) {
            $v['type'] == 1 ? $list[$k]['type_text'] = '支付宝 分润提现' : $list[$k]['type_text'] = '支付宝 佣金提现';
            $v['status'] == 1 ? $list[$k]['status_text'] = "已打款" : $list[$k]['status_text'] = "提现失败";
        }

        $this->showSuccess('', $list);
    }


    /**
     * 卡密回收
     */
    public function youka()
    {

        $uid = $this->uid;
        if (IS_POST) {

            $password = I('post.password');
            $number = I('post.number');
            $type = I('post.type');
            // $yh=D('Ptyh')->where(['uid'=>$uid])->find();
            $account = '15518311221';
            $orderid = date("YmdHis") . rand(100000, 999999);
            $price = '0.990';
            list($msec, $sec) = explode(' ', microtime());
            $timestamp = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
            $json = array(
                'account' => $account,
                'orderId' => $orderid,
                'cardNumber' => $number,
                'cardPwd' => $password,
                'face' => $type,
                'price' => $price,//与鼎信的折扣
                'effectTime' => date("Y-m-d", time() + 86400),
                'timestamp' => $timestamp,
            );
            $sign = '';
            foreach ($json as $key => $v) {
                $sign .= $key . $v;
            }
            $sign = $sign . 'eec62b20c54142188bfad1460ca6c691';
            $json['sign'] = md5($sign);
            $url = 'http://api.jiayouka.cn:11140/userApi/supply/gatewayV1';
            $res = $this->send_request($url, $json);


            $price = '0.98';

            if ($res['code'] == '10010') {
                // 受理成功  存下订单
                $data = array(

                    'uid' => $uid,
                    'orderId' => $orderid,
                    'cardNumber' => $number,
                    'cardPwd' => $password,
                    'face' => $type,
                    'yh_money' => $type * $price,
                    'price' => $price,//与商户之间的折扣
                    'time' => time(),
                    'effectTime' => date("Y-m-d", time() + 86400),
                    'status' => 1,//已受理
                    're_status' => 0,//核销状态

                );
                $id = D('Youka')->add($data);
                $this->showSuccess('提交成功');

                // 需要补充查询方法定时查询油卡是否已核销

            } else if ($res['code'] == '1005' || $res['code'] == '1009' || $res['code'] == '10017' || $res['code'] == '10021' || $res['code'] == '10022' || $res['code'] == '1005') {


                $this->showSuccess($res['message']);

            } else {

                $this->showError($res['message']);
            }
        }
    }

    /**
     * 个人资料页面
     */
    public function profile()
    {
        $info = D('Ptyh')->where("uid=" . $this->uid)->find();
        $this->showSuccess('', $info);
    }

    /**
     * 修改个人资料
     */
    public function saveProfile()
    {

        $name = I('post.name');
        $alipay = I('post.alipay');
//        $code = I('post.code');
        $identify = I('post.identify');

        $one = M('ptyh')->find($this->uid);


//        if (empty($code)) {
//            $this->showError('请输入手机验证码');
//        } else {
//            $smsLogic = new \Common\Model\SmsLogic();
//            $smsResult = $smsLogic->checkCode($one['account'],$code,'profile');
//            if($smsResult['code'] != 1)  $this->showError($smsResult['msg']);
//        }

        $id = D('Ptyh')->where(['uid' => $this->uid])->save(['name' => $name, 'alipay' => $alipay, 'identify' => $identify]);
        if ($id > 0) {
            $this->showSuccess('资料修改成功');
        } else {
            $this->showError('资料修改失败');
        }

    }

    /**
     * 修改个人资料
     */
    public function saveAvatar()
    {
        $avatar = I('avatar');

        $one = M('ptyh')->find($this->uid);


        $id = D('Ptyh')->where(['uid' => $this->uid])->save(['avatar' => $avatar]);
        if ($id > 0) {
            $this->showSuccess('资料修改成功');
        } else {
            $this->showError('资料修改失败');
        }

    }

    /***
     * 费率信息
     */
//    public function rate()
//    {
//
//        $gather = M('Gather')->where('uid=' . $this->uid)->find();
//
//        $levelRate = C('LEVEL_RATE');
//        $tongdaoAlipay = [];
//        $tongdaoBank = [];
//        foreach ($levelRate as $k => $v) {
//            $tongdaoAlipay[] = ['range' => $k, 'rate' => ($gather['up_set'] + $v)];
//            $tongdaoBank[] = ['range' => $k, 'rate' => ($gather['up_set2'] + $v)];
//        }
//        $data = [
//            'alipay' => [
//                'jichu' => ['range' => '10-399', 'rate' => $gather['up_set']],
//                'tongdao' => $tongdaoAlipay
//            ],
//            'bank' => [
//                'jichu' => ['range' => '100-50000', 'rate' => $gather['up_set2']],
////                'tongdao' => $tongdaoBank
//            ]
//        ];
//        $this->showSuccess('', $data);
//    }

    /**
     *费率信息
     */
    public function rate(){
        $gather = M('Gather')->where('uid=' . $this->uid)->find();
        $hbtd = \Home\Model\PtdataModel::getTdRate('hbtd');
        $fkhbtd = \Home\Model\PtdataModel::getTdRate('fkhbtd');
        $xyktd = \Home\Model\PtdataModel::getTdRate('xyktd');
        $dmxyktd = \Home\Model\PtdataModel::getTdRate('dmxyktd');

        $this->showSuccess('',$data = [
            'hb' => $gather['up_set'],
            'xyk' => $gather['up_set2'],
            'hbtd' => $hbtd,
            'fkhbtd' => $fkhbtd,
            'xyktd' => $xyktd,
            'dmxyktd' => $dmxyktd
        ]);
    }

    /**
     * 设置推广费率
     * 推荐下级注册时，下级默认的费率
     */
    public function setTuiGuangRate()
    {
        $child_hb_rate = floatval(I('child_hb_rate'));
        $child_xy_rate = floatval(I('child_xy_rate'));

        if($child_hb_rate*100 < 0 || $child_xy_rate*100 < 0) $this->showError('费率必须大于0');
//        $this->showSuccess('settuiguang',[$child_hb_rate,$child_xy_rate]);

        $res = M('ptyh')->where(['uid' => $this->uid])->save(['child_hb_rate' => $child_hb_rate, 'child_xy_rate' => $child_xy_rate]);
//            $this->showSuccess('res',M('ptyh')->getLastSql());
        if ($res !== false) {
            $this->showSuccess('设置成功');

        } else {
            $this->showError('设置失败');
        }

    }

    /**
     * 推广费率页面
     */
    public function getTuiGuangRate()
    {
        $gather = M('gather')->where(['uid' => $this->uid])->find();
        $ptyh = M('ptyh')->where(['uid' => $this->uid])->find();


        $huabei = $ptyh['child_hb_rate'];
        $xyk = $ptyh['child_xy_rate'];
        $huabei_rate = [];
        $xyk_rate = [];

        for ($i = 0; $i <= 3; $i++) {
            $huabei_rate[$i] = (intval($huabei * 100) + intval(5 * ($i + 1)) ) / 100;
            $xyk_rate[$i] = ($xyk * 100 + 5 * ($i + 1)) / 100;
        }

//        foreach($huabei_rate as $k => $v){
//            $huabei_rate[$k] = (intval($huabei * 100) + intval($v))/100;
//            $xyk_rate[$k] = (intval($xyk * 100) + intval($v))/100;
//        }

        $this->showSuccess('', ['hb' => $ptyh['child_hb_rate'], 'xyk' => $ptyh['child_xy_rate'], 'huabeiRate' => $huabei_rate, 'xykRate' => $xyk_rate]);
    }

    public function tuiguangfeilv($value){
        for ($i = 0; $i <= 3; $i++) {
            $data[$i] = ($value * 100 + 5 * ($i + 1)) / 100;

        }

        return $data;
    }


    /**
     * @param $request
     * @param $params
     * @param string $method
     * @param bool $https
     * @return mixed
     */
    function send_request($request, $params, $method = 'get', $https = false)
    {
        // 以get方式提交
        if ($method == 'get') {
            $request = $request . $this->create_url($params);
        }

        // return $request;

        $this->ch = curl_init($request);
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);// 设置不显示结果，储存入变量
        // curl_setopt($this->ch, CURLOPT_TIMEOUT, self::TIMEOUT); // 设置超时限制防止死循环

        // 判断是否以https方式访问
        if ($https) {
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        }

        if ($method == 'post') {        // 以post方式提交
            curl_setopt($this->ch, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params); // Post提交的数据包
        }

        $tmpInfo = curl_exec($this->ch); // 执行操作
        if (curl_errno($this->ch)) {
            echo 'Errno:' . curl_error($this->ch);//捕抓异常
        }
        curl_close($this->ch); // 关闭CURL会话
        return json_decode($tmpInfo, true);
        return $tmpInfo; // 返回数据
    }

    /**
     * @param $data
     * @return bool|string
     */
    function create_url($data)
    {
        $temp = '?';
        foreach ($data as $key => $item) {
            $temp = $temp . $key . '=' . $item . '&';
        }
        return substr($temp, 0, -1);
    }


    public function test(){
        $adata = D('Adata')->where(['id' => 1])->find();
        $remark = '信用卡二次转账给支付宝';
        //订单金额×（回款费率－成本费率）＋3（信用卡的3元手续费）
        $shoukuanma = M('shoukuanma')->where(['id' => 48])->find();
        $alipays = M('alipays')->where(['status' => 1, 'type' => 1])->find();
        $amount = 10*($shoukuanma['xyk'] - $alipays['chengben'])/100 + 3;
        echo $amount . '\n';
        $amount = number_format(floor($amount * 100) / 100, 2, '.', '');
        echo $amount;

        $n = 123.456789;

//        echo floor($n * 100) / 100;
    }

    public function test1(){
        $res = \Home\Logic\UserLogic::buildEncodeReferralCode('333666888');
        dump($res);

        $result = \Home\Logic\UserLogic::getDecodeReferralCode($res);
        echo " -- ";
        dump($result[0]);
    }



    /**
     * 平台用户绑定信息(注册)
     * @param string $phone
     * @param string $code
     * @param string $password
     * @param string $tg_num
     */
    public function register()
    {
        if (IS_POST) {

            $code = I('post.code');
            $phone = I('post.phone');
            $find = M('ptyh')->where("account=$phone")->find();
//            $this->showError('',$find);
            if($find) $this->showError('该手机号码已注册');

//            if (empty($code)) {
//
//                $this->showError('请输入手机验证码');
//            } else {
//                $smsLogic = new \Common\Model\SmsLogic();
//                $smsResult = $smsLogic->checkCode($phone,$code,'register');
//
////                $smsResult['code'] = 1;
//                if($smsResult['code'] != 1)  $this->showError($smsResult['msg']);
//
//            }

            $tg_num = I('post.tg_num','');

            $data = I('post.');
            unset($data['code']);
//            unset($data['npassword']);

            $ptdata = D("Ptdata")->where(['id' => 1])->find();
            if ($tg_num == '') {
                // 一级
                $data['password'] = md5(I('post.password'));
                $data['pid'] = 0;
                $data['level'] = 1;
                $data['yh_uid'] = $this->getUserCode();
                $data['account'] = $phone;
                $data['status'] = 1;

            } else {
                //上级数据
                $py = D('Ptyh')->where(['tg_num' => $tg_num])->find();
                $parent_gather = M('gather')->where(['uid' => $py['uid']])->find();
                $data['password'] = md5(I('post.password'));
                $data['pid'] = $py['uid'];
                $data['yh_uid'] = $this->getUserCode();
                $data['account'] = $phone;
                $data['status'] = 1;

            }


            if ($tg_num == '') {

                $data['path1'] = $ptdata['pt_rate'];
                $up_set = $ptdata['pt_rate'];
                $up_set2 = $ptdata['pt_rate2'];
                $data2 = [
                    'money' => 0,
                    'count' => 0,
                    'status' => 1,
                    'up_set' => $up_set,
                    'up_set2' => $up_set2,
                    'path1' => $ptdata['pt_rate'],
                    'path2' => $ptdata['pt_rate2'],
                    'level' => $py['level'] + 1,
                ];

            } else {

                $gather = D('Gather')->where(['uid' => $py['uid']])->find(); //上级
                $up_set = ($parent_gather['up_set']*100 + $py['child_hb_rate']*100)/100;
                $up_set2 = ($parent_gather['up_set2']*100 + $py['child_xy_rate']*100)/100;

                $data2 = [
                    'money' => 0,
                    'count' => 0,
                    'status' => 1,
                    'up_set' => $up_set,
                    'up_set2' => $up_set2,
                    'path1' => $ptdata['pt_rate'],
                    'path2' => $ptdata['pt_rate2'],
                    'level' => $py['level'] + 1,
                ];

            }


            $gather = M('Gather');

            $id2 = $gather->add($data2);
            if ($id2 > 0) {//gather存储成功再去存储用户信息

                $data['wx_uid'] = $this->wx_uid;
                $ptdata = M('ptdata')->where(['id' => 1])->find();
                //推广费率
                $data['child_hb_rate'] = ($up_set*100+$ptdata['hbtg']*100)/100;
                $data['child_xy_rate'] = ($up_set2*100+$ptdata['xyktg']*100)/100;
                $uid = D('Ptyh')->add($data);
                if ($uid > 0) {
                    $id = $gather->where(['id' => $id2])->save(['uid' => $uid]);

                    if(empty($py)){
                        $path= $uid;
                    }else{
                        $str_index = substr_count($py['path'],'/');
                        if( $str_index== 6){
                            $path = substr($py['path'],$str_index-1) . '/'.$uid;
                        }else{
                            $path=$py['path'] . '/' . $uid;
                        }




                    }
                    M('ptyh')->where(['uid' => $uid ])->save([
                        'tg_num' => \Home\Logic\UserLogic::buildEncodeReferralCode($uid),
                        'path' => $path
                    ]);
                    //增加上级的推广数量
                    \Home\Logic\UserLogic::addParentsTuiguangNum($uid);

                    \Home\Logic\UserLogic::jiandianwei($path);
                    $this->showSuccess('注册成功');
                } else {
                    // 保存不成功不需要删除用户信息，提示再次上传即可
                    $this->showError('注册失败，请稍后重试！');

                }
            } else {
                $this->showError('注册失败，请稍后重试');

            }

        }
    }


    /**
     * 获取用户编码
     * @return string
     */
    private function getUserCode()
    {
        return date('md' . rand('000000', '999999'));
    }

    /**
     * 获取用户通道费率
     * @param  string $type 类型：hbtd=花呗通道，fkhbtd=风控花呗，xyktd=信用卡通道
     * @param $uid
     * @param $money
     */
    public function getUserTdRate(){
        $type = I('type');
        $uid = I('uid');
        $money = I('money');
        $selfRate = \Home\Model\PtdataModel::getUserTdRate($type,$uid,$money);
        if(empty($selfRate)){
            $selfRate = 0;
        }

        $this->showSuccess('',$selfRate);
    }

    /**
     * 手机注册网页
     */
    public function mregister(){

        $this->display();

    }









}
